package com.xsomnus.open.zookeeper.example;

import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/18 0018 17:35
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
@Data
public class ExampleClientThatLocks {

    private final InterProcessMutex lock;

    private final FakeLimitedResource resource;

    private final String clientName;

    public ExampleClientThatLocks(CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName) {
        this.resource = resource;
        this.clientName = clientName;
        lock = new InterProcessMutex(client, lockPath);
    }

    public void doWork(long time, TimeUnit unit) throws Exception {

        if (!lock.acquire(time, unit)) {
            throw new IllegalStateException(clientName + "无法获取锁~");
        }
        try {
            System.out.println("----------------" + clientName + " 获取锁------");
            resource.use();
        } finally {
            System.out.println("----------------" + clientName + "释放锁------");
            lock.release();
        }

    }


}
